<template>
    <div id="add-edit-inventory">
        <el-dialog
            :title="titleCon"
            v-model="inventoryDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="120px" :rules="rules">
                <el-row>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="辨析范围分类" prop="v_Discriminate">
                            <el-select 
                                filterable
                                class="m-2" 
                                placeholder="请选择辨析范围分类" 
                                v-model="ruleForm.v_Discriminate" 
                                @change="eventChange"
                            >
                                <el-option
                                    v-for="item in eventOption"
                                    :key="item.id"
                                    :label="item.value"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="危害因素" prop="v_HazardousFactors">
                            <el-input v-model="ruleForm.v_HazardousFactors" placeholder="请输入危害因素" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="管控措施分类" prop="l_DCMeasureClassId">
                            <el-cascader 
                                v-model="ruleForm.l_DCMeasureClassId"
                                :options="classOption" 
                                :props="cascaderProps"
                                :show-all-levels="false" 
                                filterable
                                @change="classChange"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item label="管控措施" prop="v_DCMeasure">
                            <el-input v-model="ruleForm.v_DCMeasure" placeholder="请输入管控措施" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="隐患排查内容" prop="v_CheckContent">
                            <el-input type="textarea" v-model="ruleForm.v_CheckContent" placeholder="请输入隐患排查内容" clearable />
                        </el-form-item>
                    </el-col>
                    
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis" @click="submitForm(ruleFormRef)">提 交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , watch } from 'vue';
import { FormInstance, FormRules, ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElOption, ElRow, ElSelect } from 'element-plus';
import { SMSDCMeasureClassTrees , sysDictDataList , SMSDCListAdd, SMSDCListUpdate } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    v_Discriminate: String, // 辨析范围分类
    v_HazardousFactors: String, // 危害因素
    l_DCMeasureClassId: any, // 管控措施分类Id
    v_DCMeasure: String, // 管控措施
    v_CheckContent: String, // 隐患排查内容
    l_EventId: Number, // 风险事件Id
}
export default defineComponent( {
    name: 'add-edit-model',
    components: {},
    props: {
        inventoryDialog:{
            type: Boolean,
            default: false,
        },
        inventoryInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const eventOption = ref();
        const classOption = ref();

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** classChange 风险管控措施分类改变事件 */
        const classChange = (val: any) => {
            if(val && val.length !== 0){
                let len = val.length - 1;
                state.ruleForm.l_DCMeasureClassId = val[len];
            }
        }

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 辨析范围分类
            v_Discriminate: [
				{ required: true, message: '请选择辨析范围分类', trigger: 'change' },
			],
            // 危害因素
            v_HazardousFactors: [
                { required: true, message: '请输入危害因素', trigger: 'blur' },
            ],
            // 管控措施分类
            l_DCMeasureClassId: [
                { required: true, message: '请选择管控措施分类', trigger: 'change' },
            ],
            // 管控措施
            v_DCMeasure: [
                { required: true, message: '请输入管控措施', trigger: 'change' },
            ],
            // 隐患排查内容
            v_CheckContent: [
                { required: true, message: '请输入隐患排查内容', trigger: 'change' },
            ],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelInventoryClick')
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param: any = toRaw(state.ruleForm);
                    state.repeatDis = true;
                    try{
                        let res: any;
                        if(JSON.parse(props.inventoryInfo).status === 'add'){
                            res =  await SMSDCListAdd(param);
                        }else{
                            res = await SMSDCListUpdate(param);
                        }
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('updateData');
                            ctx.emit('controlInventoryClick');
                        }else{
                            state.repeatDis = false;
                            ctx.emit('controlInventoryClick');
                        }
                    }catch(error){ state.repeatDis = false; }
                }else{
                    console.log('error submit!')
					return false
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** getData 获取数据 */
        const getData = async() => {
            let param: any = {};
            let res: any = await SMSDCMeasureClassTrees(param);
            if(res.success) classOption.value = res.data;
            let ras: any = await sysDictDataList({ TypeCode: 'SmsDiscriminate' });
            eventOption.value = ras.data;
        }

        /*** analyChange 风险分析单元改变事件 */
        const analyChange = (val: any) => {
            console.log(val,'val')
        }

        /*** 风险事件改变事件 eventChange */
        const eventChange = (val: any) => {
            // console.log(JSON.stringify(val),'val')
        }

        /*** 监听inventoryDialog的变化 */
        watch(() => props.inventoryDialog,(newVal) => {
            if(newVal){
                getData();
                state.repeatDis = false;
                titleCon.value = '风险管控清单';
                if(JSON.parse(props.inventoryInfo).status === 'add'){
                    state.ruleForm = {
                        v_Discriminate: '', // 辨析范围分类
                        v_HazardousFactors: '', // 危害因素
                        l_DCMeasureClassId: 0, // 管控措施分类Id
                        v_DCMeasure: '', // 管控措施
                        v_CheckContent: '', // 隐患排查内容
                        l_EventId: JSON.parse(props.inventoryInfo).id, // 风险事件Id
                    }
                }else{
                    state.ruleForm = JSON.parse(props.inventoryInfo).info;
                }
            }
        })

        /*** inventoryDialog 响应弹窗的关闭  */
        const inventoryDialog = computed(() => {
            return props.inventoryDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            inventoryDialog,
            rules,
            analyChange,
            eventChange,
            eventOption,
            classChange,
            classOption,
            cascaderProps: {
                value: 'id',
                label: 'v_Name',
                children: 'children'
            }
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-dialog__body){
    height: auto!important;
    max-height: none!important;
    overflow-y: hidden;
}
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 100%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>